from datetime import datetime, timedelta, time
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.notice_center.models.nc_n9e_alarm_record import NCN9eAlarmRecord
from common.utils import CommonTimeUtils

class NCN9eAlarmRecordHandler():
    """  N9eAlarmRecord Handler
    """
    def __init__(self):
        pass


    def get_n9e_alarm_record_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取n9e告警记录信息
        """
        try:
            field_info = {field: value}
            order_info = {"status": "asc", "update_at": "desc"}
            result = NCN9eAlarmRecord.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get n9e alarm record search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get n9e alarm record search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result



    def get_n9e_alarm_record_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取n9e告警记录信息
        """
        try:
            result = NCN9eAlarmRecord.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get n9e alarm record match, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get n9e alarm record match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def update_n9e_alarm_record(self, db: Session, data: dict):
        """
        修改n9e告警记录信息
        """
        try:
            # 对接卡片信息的手机操作
            if "-" not in data["fingerprint"]:
                # 指纹结构错误， 则异常返回
                logger.error(f"update n9e alarm record failed,{data['fingerprint']} check failed")
                return False
            
            data["uuid"] = data["fingerprint"].split("-")[1]
            data["fingerprint"] = data["fingerprint"].split("-")[0]
            n9e_alarm_record_object = NCN9eAlarmRecord.get_object_by_uuid(db, data["uuid"])
            if not n9e_alarm_record_object:
                # 如果不存在， 则异常返回
                logger.error(f"update n9e alarm record failed,{data['uuid']} not exist")
                return False
            
            if data["fingerprint"] != n9e_alarm_record_object.fingerprint:
                # 如指纹不对， 则异常返回
                logger.error(f"update n9e alarm record failed,{data['fingerprint']} is error")
                return False
                      
            # 更新告警记录的屏蔽时间
            if not data["comment"]: data.pop("comment")
            result = NCN9eAlarmRecord.update(db, data)
            if not result:
                logger.error(f"update n9e alarm record to database failed")
                return False
            
            # 更新订阅记录的屏蔽时间
            n9e_subscribe_record = NCN9eAlarmRecord.get_object_info_by_fingerprint(db, data["fingerprint"], "subscribe", "firing")
            if n9e_subscribe_record:
                # 如果存在， 则同步更新屏蔽时间，更新失败也没关系，因为订阅不发送卡片
                data["uuid"] = n9e_subscribe_record["uuid"]
                NCN9eAlarmRecord.update(db, data)
            
        except Exception as e:
            message = f"update n9e alarm record error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def delete_n9e_alarm_record(self, db: Session, data: dict):
        """
        删除n9e告警记录信息
        """
        try:
            n9e_alarm_record_object = NCN9eAlarmRecord.get_object_by_uuid(db, data['uuid'])
            if not n9e_alarm_record_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete n9e alarm record failed, uuid:{data['uuid']} not exist")
                return False

            # 删除告警记录
            NCN9eAlarmRecord.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete n9e alarm record uuid:{data['uuid']}  error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




    def get_nc_n9e_alarm_status(self, db: Session):
        try:
            watchdog_info = NCN9eAlarmRecord.get_object_info_for_watchdog(db)
            if not watchdog_info:
                logger.error(f"watchdog not exist")
                return False
            
            now_timestamp = datetime.now().timestamp()
            firing_timestamp = datetime.timestamp(CommonTimeUtils.strptime(watchdog_info["update_at"]) + timedelta(minutes=15))
            if firing_timestamp < now_timestamp:
                logger.error(f"no alarm last 10 minutes  => {watchdog_info}")
                return False
            
        except Exception as e:
            message = f"get alarm status error"
            logger.exception(f"{message} => {e}")
            return False

        return True
    

    
# 测试数据
# {
# 	"id": 8034,
# 	"cate": "prometheus",
# 	"cluster": "aliyun_prod_kube_prometheus",
# 	"datasource_id": 3,
# 	"group_id": 6,
# 	"group_name": "运维",
# 	"hash": "f54d8edbe8ce8832d7644824e7ee7c17",
# 	"rule_id": 1,
# 	"rule_name": "N9eWatchDog",
# 	"rule_note": "WatchDog测试测试，请忽略。",
# 	"rule_prod": "metric",
# 	"rule_algo": "",
# 	"severity": 3,
# 	"prom_for_duration": 60,
# 	"prom_ql": "",
# 	"rule_config": {
# 		"queries": [{
# 			"prom_ql": "vector(1)",
# 			"severity": 3
# 		}]
# 	},
# 	"prom_eval_interval": 30,
# 	"callbacks": [],
# 	"runbook_url": "",
# 	"notify_recovered": 1,
# 	"notify_channels": ["nothing", "warning"],
# 	"notify_groups": ["6"],
# 	"notify_groups_obj": [{
# 		"id": 6,
# 		"name": "测试",
# 		"note": "测试",
# 		"create_at": 1687862073,
# 		"create_by": "root",
# 		"update_at": 1687862231,
# 		"update_by": "root"
# 	}],
# 	"target_ident": "",
# 	"target_note": "",
# 	"trigger_time": 1689047186,
# 	"trigger_value": "1",
# 	"tags": ["alarm=watch-dog", "rulename=N9eWatchDog"],
# 	"annotations": {},
# 	"is_recovered": 0,
# 	"notify_users_obj": [{
# 		"id": 2,
# 		"username": "boll.lai",
# 		"nickname": "boll.lai",
# 		"phone": "18682003157",
# 		"email": "boll.lai@welab-inc.com",
# 		"portrait": "",
# 		"roles": ["Admin"],
# 		"contacts": {},
# 		"maintainer": 0,
# 		"create_at": 1687858687,
# 		"create_by": "ldap",
# 		"update_at": 1687858711,
# 		"update_by": "root",
# 		"admin": 1
# 	}],
# 	"last_eval_time": 1689047186,
# 	"last_sent_time": 1689047186,
# 	"notify_cur_number": 975,
# 	"first_trigger_time": 1688726518
# }
